package com.ruicar.afs.cloud.basic.common.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.common.vo.ContractInfoForCorporateVo;
import com.ruicar.afs.cloud.basic.detail.vo.RentInfoVO;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.AssetTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProductAtomEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ReceiptStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-07-16 20:03
 */
@Slf4j
@RestController
@RequestMapping("/related")
@AllArgsConstructor
public class RelatedInfoController {

    private final BasicMainInfoService basicMainInfoService;

    private final BasicRepaymentPlanService basicRepaymentPlanService;

    private final BasicCustBaseInfoService basicCustBaseInfoService;

    private final BasicContractCustRelationService basicContractCustRelationService;

    private final BasicFinancialAgreementService basicFinancialAgreementService;

    private final BasicDebitInfoService basicDebitInfoService;

    private final BasicReceiptRecordService basicReceiptRecordService;

    private final BasicProductParamService basicProductParamService;


    /**
     * 对公结算相关合同信息查询
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/contractInfoForCorporate")
    @ApiOperation(value = "对公结算相关合同信息查询")
    @Transactional(rollbackFor = Exception.class)
    public IResponse contractInfoForCorporate(@RequestParam("contractNo") String contractNo) {
        ContractInfoForCorporateVo contractInfoForCorporateVo = new ContractInfoForCorporateVo();

        /**  合同基本信息 by ZC.GUO  **/
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,contractNo)
        );
        if (EmptyUtils.isNotEmpty(mainInfo)){
            contractInfoForCorporateVo.setContractNo(mainInfo.getContractNo());
            contractInfoForCorporateVo.setApplyNo(mainInfo.getApplyNo());
            contractInfoForCorporateVo.setStartDate(mainInfo.getStartDate());
            contractInfoForCorporateVo.setEndDate(mainInfo.getEndDate());
            contractInfoForCorporateVo.setContractStatus(mainInfo.getContractStatus());
            contractInfoForCorporateVo.setChannelName(mainInfo.getChannelFullName());
            contractInfoForCorporateVo.setChannelType(mainInfo.getChannelType());
            contractInfoForCorporateVo.setProductName(mainInfo.getProductName());
        }else{
            return IResponse.fail("合同号码无数据");
        }

        /**  还款信息 by ZC.GUO  **/
        List<RentInfoVO> rentInfoVOs = basicRepaymentPlanService.queryRepaymentInfo(contractNo,null);
        if(EmptyUtils.isNotEmpty(rentInfoVOs)){
            RentInfoVO rentInfoVO = rentInfoVOs.get(0);
            if (EmptyUtils.isNotEmpty(rentInfoVO)){
                contractInfoForCorporateVo.setPaidTerms(rentInfoVO.getPaidTerm());
                contractInfoForCorporateVo.setUnpaidTerms(rentInfoVO.getUnpaidTerm());
            }
        }


        /**  借款人信息 by ZC.GUO  **/
        BasicContractCustRelation contractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>query().lambda()
                .eq(BasicContractCustRelation::getContractNo,contractNo)
                .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
        );

        if (EmptyUtils.isNotEmpty(contractCustRelation)){
            BasicCustBaseInfo custBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda()
                    .eq(BasicCustBaseInfo::getCustNo,contractCustRelation.getCustNo())
            );
            if (EmptyUtils.isNotEmpty(custBaseInfo)){
                contractInfoForCorporateVo.setCustName(custBaseInfo.getCustName());
                contractInfoForCorporateVo.setCertNo(custBaseInfo.getCertNo());
                contractInfoForCorporateVo.setPhone(custBaseInfo.getPhone());
            }
        }

        /**  金融协议信息 by ZC.GUO  **/
        BasicFinancialAgreement financialAgreement = basicFinancialAgreementService.getOne(Wrappers.<BasicFinancialAgreement>query().lambda()
                .eq(BasicFinancialAgreement::getContractNo,contractNo)
                .eq(BasicFinancialAgreement::getCostType, AssetTypeEnum.CAR_AMT)
        );

        if (EmptyUtils.isNotEmpty(financialAgreement)){
            contractInfoForCorporateVo.setLoanTerm(financialAgreement.getLoanTerm());
            contractInfoForCorporateVo.setMonthPayAmt(financialAgreement.getMonthPayAmt());
            contractInfoForCorporateVo.setDownPayAmt(financialAgreement.getDownPayAmt());
            contractInfoForCorporateVo.setLoanAmt(financialAgreement.getLoanAmt());
        }

        /**  当前逾期天数 by ZC.GUO  **/
        BasicDebitInfo debitInfo = basicDebitInfoService.getOne(Wrappers.<BasicDebitInfo>query().lambda()
                .eq(BasicDebitInfo::getContractNo,contractNo)
        );
        if (EmptyUtils.isNotEmpty(debitInfo)){
            contractInfoForCorporateVo.setOverdueDaysHis(debitInfo.getCurrentAbsoluteOverdue());
        }
        /**  当期总应收 by ZC.GUO  **/
        BasicRepaymentPlan repaymentPlan = basicRepaymentPlanService.calculateRepaymentInfo(basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
                .ne(BasicRepaymentPlan::getTermNo, BigDecimal.ZERO.intValue())
                .orderByAsc(BasicRepaymentPlan::getTermNo)
        ));
        if (EmptyUtils.isNotEmpty(repaymentPlan)){
            contractInfoForCorporateVo.setCurrentReceivable(repaymentPlan.getReceivableRent());
        }
        /**  上次付款时间 by ZC.GUO  **/
        List<BasicReceiptRecord> receiptRecordList = basicReceiptRecordService.list(Wrappers.<BasicReceiptRecord>query().lambda()
                .eq(BasicReceiptRecord::getContractNo,mainInfo.getContractNo())
                .ne(BasicReceiptRecord::getReceiptStatus, ReceiptStatusEnum.revoke)
        );
        if (EmptyUtils.isNotEmpty(receiptRecordList)){
            contractInfoForCorporateVo.setLastPayTime(receiptRecordList.get(0).getCreateTime());
        }
        /**  利率类型 by ZC.GUO  **/
        BasicFinancialAgreement basicFinancialAgreement = basicFinancialAgreementService.getOne(Wrappers.<BasicFinancialAgreement>lambdaQuery()
                .eq(BasicFinancialAgreement::getContractNo, mainInfo.getContractNo())
                .eq(BasicFinancialAgreement::getCostType, AssetTypeEnum.CAR_AMT));
        BasicProductParam productParam = basicProductParamService.getOne(Wrappers.<BasicProductParam>lambdaQuery()
                .eq(BasicProductParam::getContractNo, mainInfo.getContractNo())
                .eq(BasicProductParam::getAtomKey, ProductAtomEnum.RATE_TYPE)
                .eq(BasicProductParam::getProductId, basicFinancialAgreement.getProductId()));
        if (EmptyUtils.isNotEmpty(productParam)) {
            contractInfoForCorporateVo.setRateType(productParam.getAtomValue());
        }
        return IResponse.success(contractInfoForCorporateVo);
    }
}
